"""
2022  B圈新版课程 | 邢不行
author: 邢不行
微信: xbx6660
"""
import base64
import hashlib
import hmac
import json
import time
from urllib import parse

import pandas as pd
import requests

from datetime import datetime

from 布林策略实盘.config import secret, webhook


def cal_timestamp_sign(secret):
    # 根据钉钉开发文档，修改推送消息的安全设置https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq
    # 也就是根据这个方法，不只是要有webhook，还要有secret
    # 当前时间戳，单位是毫秒，与请求调用时间误差不能超过1小时
    # python3用int取整
    timestamp = int(round(time.time() * 1000))
    # 密钥，机器人安全设置页面，加签一栏下面显示的SEC开头的字符串
    secret_enc = bytes(secret.encode('utf-8'))
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = bytes(string_to_sign.encode('utf-8'))
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    # 得到最终的签名值
    sign = parse.quote_plus(base64.b64encode(hmac_code))
    return str(timestamp), str(sign)


def send_dingding_msg(content):
    try:
        msg = {
            "msgtype": "text",
            "text": {"content": datetime.now().strftime("%m-%d %H:%M:%S") + '\n' + content}
        }
        headers = {"Content-Type": "application/json;charset=utf-8"}
        # https://oapi.dingtalk.com/robot/send?access_token=XXXXXX&timestamp=XXX&sign=XXX
        timestamp, sign_str = cal_timestamp_sign(secret)
        url = 'https://oapi.dingtalk.com/robot/send?access_token=' + webhook + \
              '&timestamp=' + timestamp + '&sign=' + sign_str
        body = json.dumps(msg)
        requests.post(url, data=body, headers=headers, timeout=10)
        print('成功发送钉钉\n')
    except Exception as e:
        print(f"发送钉钉失败:{e}\n")


def send_dingding_msg_for_position(equity, account_info):
    '''
    发送账户信息和净值到钉钉
    '''
    dingding_msg = f'账户净值：{equity:8.2f}\n'
    account_info["持仓收益"] = account_info["持仓收益"]
    if not account_info.empty:
        dingding_msg += f'当前持仓未实现盈亏：{account_info["持仓收益"].sum():8.2f}\n'
        dingding_msg += '策略持仓：\n'
        for index, row in account_info.iterrows():
            if row['持仓量'] != 0:
                dingding_msg += str(index)
                dingding_msg += row[['持仓量', '持仓均价', '持仓收益']].to_string()
                dingding_msg += '\n'
    if not dingding_msg.endswith('策略持仓：\n'):
        send_dingding_msg(dingding_msg)


def send_dingding_msg_for_order(order_param, order_res):
    """
    发送下单信息到钉钉
    """
    dingding_msg = ''
    for _ in range(len(order_param)):
        dingding_msg += f'币种:{order_param[_]["symbol"]}\n'
        dingding_msg += f'方向:{"做多" if order_param[_]["side"] == "BUY" else "做空"}\n'
        dingding_msg += f'价格:{order_param[_]["price"]}\n'
        dingding_msg += f'数量:{order_param[_]["quantity"]}\n'

        if 'msg' in order_res[_].keys():
            dingding_msg += f'下单结果:{order_res[_]["msg"]}'
        else:
            dingding_msg += f'下单结果: 下单成功'

        dingding_msg += '\n' * 2

    send_dingding_msg(dingding_msg)


if __name__ == '__main__':
    equity = 50
    account_info = pd.read_csv('.././data/account_info.csv', index_col=0)
    send_dingding_msg_for_position(equity, account_info)
